package base.serialized;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerialAlien {

	public static void main(String[] args) throws Exception {

		fileFreeze();
		fileUnfreeze();
		
//		byteUnfreeze(byteFreeze());

	}

	public static void fileFreeze() throws Exception {

		Alien alien = initAlien();

		ObjectOutputStream stream = new ObjectOutputStream(
				new FileOutputStream("alien.out"));

		stream.writeObject(alien);
	}

	public static ByteArrayOutputStream byteFreeze() throws Exception {

		Alien alien = initAlien();

		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		ObjectOutputStream stream = new ObjectOutputStream(bos);

		stream.writeObject(alien);

		return bos;
	}

	public static void fileUnfreeze() throws Exception {
		ObjectInputStream stream = new ObjectInputStream(new FileInputStream(
				"alien.out"));

		Alien alien = (Alien) stream.readObject();

		System.out.println(alien);
	}

	public static void byteUnfreeze(ByteArrayOutputStream bos) throws Exception{
		
		ObjectInputStream stream=new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
		
		Alien alien=(Alien) stream.readObject();
		
		System.out.println(alien);	
	}

	private static Alien initAlien() {
		Alien alien = new Alien();
		alien.setName("alien");
		alien.setProduct("wap");
		alien.setVersion("1.0.0");
		alien.setPwd("password");
		return alien;
	}

}

class Alien implements Serializable {

	private static final long serialVersionUID = -9188670386566817247L;

	private String name;
	private String version;
	private String product;
	private transient String pwd;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public String getProduct() {
		return product;
	}

	public void setProduct(String product) {
		this.product = product;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String toString() {
		return "name:" + name + "\nversion:" + version + "\nproduct:" + product+"\npwd:"+pwd;
	}

}
